/*
 * @Author: 张仁会 28396543@qq.com
 * @Date: 2022-03-31 11:44:03
 * @LastEditors: 张仁会 28396543@qq.com
 * @LastEditTime: 2022-09-03 10:48:02
 * @FilePath: \project-2018a-3e:\课程\9项目实战\专4课件\day3：文件上传和下载+express快速搭建\exp-jwt\app.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var mysql = require('mysql');

var expressJwt = require('express-jwt');

var indexRouter = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors()); // 跨域

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 模块路由请求之前
app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// mysql只初始化一次，后续直接拿来使用
// 创建一个连接
const connection = mysql.createConnection({
  host: 'localhost', // ip // 默认端口号：3306
  port: 3306, // 修改端口号
  user: 'root', // 用户名 root
  password: 'rootroot', // 密码 rootroot
  database: 'store_system' // 数据库
});

// 连接mysql(必须执行)
connection.connect()
console.log("mysql连接成功");

// 共享mysql链接
global.connection = connection

// 共享sql语句执行方法
global.query = (sql) => {
  return new Promise((resolve, reject) => {
    connection.query(sql, function (error, results, fields) {
      if (error) {
        reject(error)
      } else {
        resolve(results) // select * from user [{}]
      }
    })
  })
}


module.exports = app;
